package com.zrf.gulimall.auth.controller;

import com.zrf.gulimall.auth.feign.MemberFeign;
import com.zrf.gulimall.auth.vo.UserLoginVo;
import com.zrf.gulimall.commnon.core.response.Resp;
import com.zrf.gulimall.commnon.core.vo.MemberResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * todo 缺少手机验证码注册功能，后续完善
 * @Author zhanrf
 * @Date 2021/12/27 22:31
 */
@Controller
public class LoginController {

	@Autowired
	private MemberFeign memberFeign;

	@PostMapping("/login")
	public String login(UserLoginVo userLoginVo, RedirectAttributes attributes, HttpSession session) {
		//远程登录
		Resp<MemberResponseVo> resp = memberFeign.getMember(userLoginVo.getLoginacct(), userLoginVo.getPassword());

		if (resp.getCode() == 0) {
			MemberResponseVo data = resp.getData();
			session.setAttribute("loginUser",data);
			return "redirect:http://gulimall.com";
		}
		Map<String,String> errors = new HashMap<>();
		errors.put("msg",resp.getMsg());
		attributes.addFlashAttribute("errors",errors);
		return "redirect:http://auth.gulimall.com/login.html";
	}

	@GetMapping(value = "/login.html")
	public String loginPage(HttpSession session) {
		//从session先取出来用户的信息，判断用户是否已经登录过了
		Object attribute = session.getAttribute("loginUser");
		//如果用户没登录那就跳转到登录页面
		if (attribute == null) {
			return "login";
		} else {
			return "redirect:http://gulimall.com";
		}
	}

	@GetMapping(value = "/loguot.html")
	public String logout(HttpServletRequest request) {
		request.getSession().removeAttribute("loginUser");
		request.getSession().invalidate();
		return "redirect:http://gulimall.com";
	}

}
